﻿using System;
using System.Linq;
using Microsoft.TeamFoundation.Client;

namespace Broadbeach.Core
{
    public class Application
    {
        private readonly string _baseAddress;
        private readonly string _collectionUri;
        private readonly string _scriptPath;
        private TfsEventListener _listener;

        public Application(string baseAddress, string collectionUri, string scriptPath)
        {
            _baseAddress = baseAddress;
            _collectionUri = collectionUri;
            _scriptPath = scriptPath;
        }

        public void Start()
        {
            var collectionUris = new[] { new Uri(_collectionUri) };
            var collections = collectionUris.Select(TfsTeamProjectCollectionFactory.GetTeamProjectCollection);

            var scriptServerPathProvider = new ScriptServerPathProvider();
            foreach (var collection in collections)
            {
                scriptServerPathProvider.Add(collection, _scriptPath);
            }

            var processor = new WorkItemChangedEventProcessor(scriptServerPathProvider);
            _listener = new TfsEventListener(TfsEventListener.WorkItemChangedEventName, new Uri(_baseAddress), collections, processor);
        }

        public void Stop()
        {
            _listener.Dispose();
        }
    }
}